package com.tange.ai.iot.client.gnssa.newui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.util.Consumer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.tange.ai.iot.client.gnssa.R;
import com.tange.ai.iot.client.gnssa.bean.BleSLDevice;
import com.tange.ai.iot.client.gnssa.bean.LoginBean;
import com.tange.ai.iot.client.gnssa.bean.RespMsg;
import com.tange.ai.iot.client.gnssa.binding.WiFiListAdapter;
import com.tange.ai.iot.client.gnssa.home.HomeActivity;
import com.tange.ai.iot.client.gnssa.httpservice.DeviceService;
import com.tange.ai.iot.client.gnssa.token.InternalAccountLoginActivity;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.ui.design.BasicDialogLoading;
import com.tange.base.ui.design.BasicDialogRequest;
import com.tange.core.access.token.Authentication;
import com.tange.core.access.token.Token;
import com.tange.core.data.structure.Resp;
import com.tange.feature.binding.prepare.DeviceBindingConfiguration;
import com.tange.feature.binding.search.DeviceBindingSearchWiFi;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import base.activity.BaseActivity;
import base.http.rxandroid.CustomDisposableForJava;
import base.http.utils.RetrofitManager;
import base.utils.LogUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class WiFiActivity extends BaseActivity {


    private EditText wifiName;
    private EditText wifiPwd;
    private Button next;
    private RecyclerView wifiList;
    private TextView wifiEmptyView;
    private LinearLayout container;


    private DeviceBindingSearchWiFi wifiSearch;

    private WiFiListAdapter listAdapter;

    private BasicDialogLoading loading;
    private ArrayList<BleSLDevice> selectBleList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_wifi;
    }

    @Override
    protected void initData() {
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarDarkFont(true).init();

        wifiName = findViewById(R.id.wifi_name);
        wifiPwd = findViewById(R.id.wifi_pwd);
        next = findViewById(R.id.next);
        wifiList = findViewById(R.id.wifi_list);
        wifiEmptyView = findViewById(R.id.wifi_empty_view);
        container = findViewById(R.id.container);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                create();
            }
        });

        listAdapter = new WiFiListAdapter();
        listAdapter.setOnSelected(new Consumer<String>() {
            @Override
            public void accept(String s) {
                wifiName.setText(s);
            }
        });
        wifiList.setAdapter(listAdapter);

        wifiList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL,false));

        wifiSearch=new DeviceBindingSearchWiFi(this, new Consumer<Resp<List<String>>>() {
            @Override
            public void accept(Resp<List<String>> listResp) {
                if(listResp.getSuccess()){
                    listAdapter.refreshApList(listResp.getData());
                }else{
                    Toast.makeText(mContext, "扫描失败：${it.code}, ${it.message}", Toast.LENGTH_LONG).show();
                }
            }
        });
        wifiSearch.start();
    }

    private void create() {
        String ssid = wifiName.getText().toString().trim();
        String pwd = wifiPwd.getText().toString().trim();

        if (TextUtils.isEmpty(ssid)) {
            Toast.makeText(this, "Empty SSID", Toast.LENGTH_LONG).show();
            return;
        }

        if (loading!=null &&loading.isShowing() == true) {
            loading.dismiss();
        }

        loading = new BasicDialogLoading(this);
        loading.setMessage("正在生成绑定配置信息...");
        loading.show();

        DeviceBindingConfiguration.create(ssid, pwd, new Consumer<Resp<String>>() {
            @Override
            public void accept(Resp<String> configure) {
                loading.dismiss();

                if (configure.getSuccess()) {
                    String data = configure.getData();
                    Bundle bundle = new Bundle();
                    bundle.putString("configeData",data);
                    bundle.putString("ssid",ssid);
                    bundle.putString("pwd",pwd);
                    readyGo(WiFiConfigActivity.class,bundle);
                    EventBus.getDefault().postSticky(new EventBusEntity("BLE",selectBleList));
                } else {
                    BasicDialogRequest basicDialogRequest = new BasicDialogRequest(mContext);
                    basicDialogRequest.setMessage("生成绑定配置信息失败：${configure.message}");
                    basicDialogRequest.setPositiveText("知道了");
                    basicDialogRequest.setPositiveOnClicked(new Function1<View, Unit>() {
                        @Override
                        public Unit invoke(View view) {
                            basicDialogRequest.dismiss();
                            return null;
                        }
                    });
                    basicDialogRequest.show();
                }
            }
        }) ;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(wifiSearch!=null){
            wifiSearch.stop();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN ,sticky = true)
    public void onBleDataGet(EventBusEntity entity) {
        try {
            if (entity.tag.equals("BLE")) {
                selectBleList= (ArrayList<BleSLDevice>) entity.data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
